import {EventsEmit, EventsOnce} from "frontend/src/wailsjs/runtime";
import {nanoid} from "nanoid";

export interface Response<T = any> {
    Data: T
}

export interface Request<T = any> {
    channel: string
    type: string
    payload?: T
}

const event = "system"

export interface Disk {
    device:     string;
    mountpoint: string;
    fstype:     string;
    opts:       string;
}

export interface FileEntry {
    Path:      string;
    Name:      string;
    IsDir:     boolean;
    IsSymlink: boolean;
    ModTime:   string;
    Size:      number;
}

export function GetDiskPartitions(){
    return new Promise<Disk[]>(resolve => {
        let channel = nanoid()
        EventsOnce(channel,(data:Response<Disk[]>)=>{
            console.log(data)
            resolve(data.Data)
        })

        EventsEmit(event,JSON.stringify(<Request>{
            channel: channel,
            type: "disk:partitions"
        }))
    })
}

export function GetDiskUsage(path:string){
    return new Promise(resolve => {
        let channel = nanoid()
        EventsOnce(channel,(data:Response)=>{
            resolve(data.Data)
        })

        EventsEmit(event,JSON.stringify(<Request<string>>{
            channel: channel,
            type: "disk:usage",
            payload: path
        }))
    })
}

export function ScanDir(path:string){
    return new Promise<FileEntry[]>(resolve => {
        let channel = nanoid()
        EventsOnce(channel,(data:Response<FileEntry[]>)=>{
            resolve(data.Data)
        })

        EventsEmit(event,JSON.stringify(<Request<string>>{
            channel: channel,
            type: "disk:scan",
            payload: path
        }))
    })
}

let defined = {
    disk: {
        GetDiskPartitions,
        GetDiskUsage,
        ScanDir
    }
};

(window as any).system = defined

export default defined